package com.cc.sanjieduan.security.handlers;

import com.cc.sanjieduan.pojo.BaseUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.cc.sanjieduan.cache.RoleCache;
import com.cc.sanjieduan.dto.R;
import com.cc.sanjieduan.mapper.RoleMapper;
import com.cc.sanjieduan.pojo.Menu;
import com.cc.sanjieduan.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyAuthenSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private ObjectMapper objectMapper;

    private RoleMapper roleMapper;

    private RoleCache roleCache;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }
    @Autowired
    public void setRoleCache(RoleCache roleCache) {
        this.roleCache = roleCache;
    }

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //super.onAuthenticationSuccess(request, response, authentication);
        BaseUser principal = (BaseUser) authentication.getPrincipal();//获取当前登录的用户,类似于session中保存了用户的数据.这个结果就是我们的MyUserDetailService中方法的返回值
       // String username = principal.getUsername();//获取到登录的用户名
        Long userId = principal.getUserId();
       // Collection grantedAuthorities = authentication.getAuthorities();//获取用户现在已经有的权限
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        List<Long> roleIds = roleMapper.selectRoleIdByUserId(userId);//查询到了用户相关的所有的角色的id
        roleIds.stream().forEach(roleId->{//遍历用户所有的角色
            Role role = roleCache.getValue(roleId);//获取到当前角色id对应的角色
            List<Menu> menuList = role.getMenuList();//用户能访问的菜单集合
            //把每个菜单的权限获取出来设置给当前用户就可以
            //List<SimpleGrantedAuthority> authorityList = menuList.parallelStream().map(Menu::getPerms).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
           // grantedAuthorities.addAll(authorityList);//将权限添加给用户
            authorityList.addAll(menuList.parallelStream().map(Menu::getPerms).map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        });
        //重新设置权限
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(principal,authentication.getCredentials(),authorityList));
        response.setContentType("application/json;charset=utf-8");
       // context.publishEvent(new UserLoginEvent());
        R r = R.setOK();
        response.getWriter().write(objectMapper.writeValueAsString(r));
    }
}
